Page({
  data: {
    language: 'zh',
    avatarUrl: '',
    username: '',
    email: '',
    phone: '',
    bio: '',
    userInfo: {}
  },

  onLoad() {
    // Load saved language preference
    const savedLanguage = wx.getStorageSync('language') || 'zh';
    this.setData({
      language: savedLanguage
    });
    
    // Load user info
    this.loadUserInfo();
  },

  loadUserInfo() {
    const app = getApp();
    const userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {};
    this.setData({
      userInfo: userInfo,
      username: userInfo.username || '',
      email: userInfo.email || '',
      phone: userInfo.phone || '',
      bio: userInfo.bio || '',
      avatarUrl: userInfo.avatarUrl || ''
    });
  },

  toggleLanguage() {
    const newLanguage = this.data.language === 'zh' ? 'en' : 'zh';
    this.setData({
      language: newLanguage
    });
    
    // Save language preference
    wx.setStorageSync('language', newLanguage);
  },

  changeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.setData({
          avatarUrl: tempFilePath
        });
        
        wx.showToast({
          title: this.data.language === 'zh' ? '头像已更新' : 'Avatar updated',
          icon: 'success'
        });
      },
      fail: () => {
        wx.showToast({
          title: this.data.language === 'zh' ? '选择图片失败' : 'Failed to choose image',
          icon: 'none'
        });
      }
    });
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onEmailInput(e) {
    this.setData({
      email: e.detail.value
    });
  },

  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  onBioInput(e) {
    this.setData({
      bio: e.detail.value
    });
  },

  saveProfile() {
    // Save user info
    const userInfo = {
      username: this.data.username,
      email: this.data.email,
      phone: this.data.phone,
      bio: this.data.bio,
      avatarUrl: this.data.avatarUrl
    };
    
    wx.setStorageSync('userInfo', userInfo);
    
    // Update global data
    const app = getApp();
    app.globalData.userInfo = userInfo;
    
    wx.showToast({
      title: this.data.language === 'zh' ? '保存成功' : 'Saved successfully',
      icon: 'success'
    });
  },

  logout() {
    // Clear user info
    wx.removeStorageSync('userInfo');
    const app = getApp();
    app.globalData.isLoggedIn = false;
    app.globalData.userInfo = null;
    
    wx.showToast({
      title: this.data.language === 'zh' ? '已退出登录' : 'Logged out',
      icon: 'success'
    });
    
    // Navigate to login page
    wx.redirectTo({
      url: '/pages/login/login'
    });
  }
});